package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.entity.Brand;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    // 分页查询
    @Override
    public PageDTO<BrandDTO> queryPage(Long page, Long rows, String key) {

        // 分页条件对象
        Page<Brand> info = new Page<>(page, rows);

        // 判断key是否为空
        boolean isKeyExits = StringUtils.isNoneBlank(key);
        //如果key存在则添加like和eq查询条件，否则不添加
        query().like(isKeyExits,"name",key)
                .or()
                .eq(isKeyExits,"letter",key).page(info);


        // 封装查询结果
        List<Brand> brandList = info.getRecords();
        return new PageDTO<>(info.getTotal(),info.getSize(),BrandDTO.convertEntityList(brandList));
    }


    /*
    *  根据分类id查询品牌
    *   手机  小米品牌
    *   手机  华为品牌
    * */
    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long id) {

        List<Brand> list = getBaseMapper().queryBrandByCategoryId(id);
        return BrandDTO.convertEntityList(list);

    }

    /*
    新增商品品牌
    */
    @Override
    @Transactional
    public void addBrand(BrandDTO brandDTO) {
        //新增品牌，新增品牌分类表
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);

         /* // 2.获取分类id， 包含手机、空调、洗衣机
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 3.封装中间表对象集合
        Long brandId = brand.getId();// 小米

        List<CategoryBrand> categoryBrands = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            // 创建中间表对象
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }*/
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }

    /*
    * 修改
    * */
    @Override
    public void updateBrand(BrandDTO brandDTO) {


        //更新品牌表，
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean success = updateById(brand);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败！");
        }
        // 更新品牌分类表 先删除 在加

        boolean remove = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!remove) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败，删除中间表数据出错");
        }
        //向中间表插入数据
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream().map(
                id -> CategoryBrand.of(id, brandDTO.getId())
        ).collect(Collectors.toList());

        categoryBrandService.saveBatch(list);
    }

}
